//
//  TrainRefundAController.swift
//  AirTravel
//
//  Created by apple on 2021/8/28.
//

import UIKit
import Moya
import SwiftyJSON

class TrainRefundAController: UIViewController {

    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var submitBtn: UIButton!
    let identifyTTD = "TrainTimeDetailsCell"
    let identifyTRP = "TrainRefundPeopleCell"
    var dataDic : Dictionary<String,Any>?
    var seatDic : Dictionary<String,Any>?
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var ps_id = ""
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.black]
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.white]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "退票申请"
        self.submitBtn.layer.cornerRadius = 6
        self.submitBtn.layer.masksToBounds = true
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "TrainTimeDetailsCell", bundle: nil), forCellReuseIdentifier: identifyTTD)
        self.tabView.register(UINib.init(nibName: "TrainRefundPeopleCell", bundle: nil), forCellReuseIdentifier: identifyTRP)
        
        if let dic = self.seatDic {
            self.ps_id = "\(dic["ps_id"] ?? "")"
        }
    }


    @IBAction func submit(_ sender: Any) {
        if let dic = self.dataDic {
            let order_id = "\(dic["orderId"] ?? "")"
            cancelableRequest = NetWorkRequest(API1.orderRefund(parameters: ["order_id":"\(order_id)","ps_id":"\(self.ps_id)"]), completion: {[weak self] (responseString) -> (Void) in
                let refund_status = responseString["data"]["refund_status"].boolValue
                let refund_fee = responseString["data"]["refund_fee"].stringValue
                
                if refund_status == true {
                    let  alertController =  UIAlertController (title:  "温馨提示" ,message:  "退款成功，退款手续费￥\(refund_fee)" , preferredStyle: .alert )
                    let okAction =  UIAlertAction.init(title: "好的", style: .default) { act in
                        self?.navigationController?.popViewController(animated: true)
                    }
                    alertController.addAction(okAction)
                    self?.present(alertController, animated: true , completion:  nil )
                }else{
                    YProgressHUD.showToast("退款失败")
                }
            }, failed: { (failedResutl) -> (Void) in
                print("服务器返回code不为0000啦~\(failedResutl)")
            }, errorResult: { () -> (Void) in
                print("网络异常")
            })
        }
        
        
    }
    
}

extension TrainRefundAController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTTD) as! TrainTimeDetailsCell
            cell.selectionStyle = .none
            if let dic = self.dataDic {
                cell.start_dateOfLab.text = "\(dic["departDate"] ?? "")"
                cell.start_hoursLab.text = "\(dic["departTime"] ?? "")"
                cell.start_standingLab.text = "\(dic["fromStationName"] ?? "")"
                cell.end_dateOfLab.text = "\(dic["arriveDate"] ?? "")"
                cell.end_hoursLab.text = "\(dic["arriveTime"] ?? "")"
                cell.terminalLab.text = "\(dic["toStationName"] ?? "")"
                cell.trainsLab.text = "\(dic["trainNo"] ?? "")"
                cell.journey_timeLab.text = "\(dic["useTime"] ?? "")"
            }
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTRP) as! TrainRefundPeopleCell
            cell.selectionStyle = .none
            if let dic = self.seatDic {
                cell.nameLab.text = "\(dic["name"] ?? "")"
                cell.idCardLab.text = "\(dic["number"] ?? "")"
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 121
        default:
            return 110
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    }
}
